{% extends "core.twig" %}

{% block content %}

<link rel="stylesheet" type="text/css" href="/static/css/svelte/controls.css?v={{ COMMIT_SHA }}">
<link rel="stylesheet" type="text/css" href="/static/css/svelte/publish.css?v={{ COMMIT_SHA }}">
<link rel="stylesheet" type="text/css" href="/static/css/svelte/publish/guest.css?v={{ COMMIT_SHA }}">

<script type="text/javascript" src="{{workflow.path_js}}"></script>
<link rel="stylesheet" type="text/css" href="{{workflow.path_css}}">

{% if user.isLoggedIn() %}
{{ svelte('chart-breadcrumb', {folders:folders, type:visNamespace}) }}
{% endif %}

{{ hook('before_editor_nav', chart) }}
{{ hook('visualize_before_svelte_sidebar', chart) }}

<div class="svelte-editor-base" id="svelte-workflow-{{ workflow.id }}"></div>

<script type="text/javascript">

require(['{{workflow.module}}'], function(mod) {

    var App = mod.App,
        data = _.extend({
            active: {{chart.lastEditStep}},
            maxStep: {{chart.lastEditStep}},
            step: '{{step}}',
            visualization: {{vis|json|raw}},
            customFields: {{customFields|json|raw}}
        },
        mod.data || {},
        {{workflow.data|json|raw }} || {});

    var chart = new mod.Chart({{chart.toStruct()|json|raw}});
    var getJSON = mod.utils.getJSON;

    var themeCache = {};
    themeCache['{{theme.id}}'] = {{theme.themeData|json|raw}};

    chart.set({
        writable: true,
        themeData: themeCache['{{theme.id}}'],
        user: {{userArray|json|raw}},
        locales: {{chartLocales|json|raw}},
        actions: {{chartActions|json|raw}},
        themes: {{userThemes|json|raw}},
        flags: {{flags|json|raw}},
        dataset: chartData ? JSON.parse(chartData) : {},
        apiDomain: '{{apiDomain}}',
        teamSettings: {{ teamSettings|json|raw }},
        customLayouts: {{customLayouts|json}}
    });

    var publishData = {{ publishData | json | raw }};

    {% if publishLogic %}
    var pubLogic = {{ publishLogic | json | raw }};
    pubLogic.data = _.extend({}, publishData, pubLogic.data);
    {% else %}
    var pubLogic = { data: publishData };
    {% endif %}

    chart.set({
        publishLogic: pubLogic
    });

    if (window.location.pathname.split('/')[3] != '{{step}}') {
        window.history.replaceState({id:'{{chart.id}}'}, '', '/edit/{{chart.id}}/{{step}}');
    }

    var lastHash = null;

    {% if user.isAdmin %}window.chart = chart;{% endif %}

    var editHistory = [];
    var dontPush = false;
    var historyPos = 0;

    chart.on('state', ({changed, current, previous}) => {
        // observe theme changes and load new theme data if needed
        if (changed.theme) {
            if (themeCache[current.theme]) {
                // re-use cached theme
                chart.set({themeData: themeCache[current.theme]});
            } else {
                // load new theme data
                getJSON(`//${dw.backend.__api_domain}/v3/themes/${current.theme}?extend=true`, (res) => {
                    themeCache[current.theme] = res.data;
                    chart.set({themeData: res.data});
                });
            }
        }

        if (previous && changed.title || changed.theme || changed.type ||
            changed.metadata || changed.language || changed.lastEditStep) {
            chart.store();
            if (!dontPush) {
                const s = JSON.stringify(chart.serialize());
                if (historyPos > 0) {
                    // throw away edit history until the current pos
                    editHistory.splice(0, historyPos);
                }
                if (editHistory[0] != s) editHistory.unshift(s);
                editHistory.length = Math.min(editHistory.length, 50);
                historyPos = 0;
            }
        }

        if (changed.dataset) {
            chart.storeData();
        }
    });

    window.addEventListener('keypress', function(evt) {
        if (evt.key == 'z' && evt.ctrlKey) {
            const old_pos = historyPos;
            historyPos += evt.altKey ? -1 : 1;
            if (editHistory[historyPos]) {
                dontPush = true;
                chart.set(JSON.parse(editHistory[historyPos]));
                dontPush = false;
            } else {
                historyPos = old_pos;
            }
        }
    });

    var chartData = {{chart.loadData()|json|raw}};//'.replace(/\n/g, '\\n');
    chart.load(chartData || 'X.1').then(function() {
        var app = mod.app = new App({
            store: chart,
            target: document.querySelector('#svelte-workflow-{{ workflow.id }}'),
            data: data
        });
    });
});
</script>


{% endblock %}
